package com.bilibili.juc.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @author zuife
 * @description
 * @since 2024-05-04 20:04:47
 */
public class AtomicMarkableReferenceDemo {
    static AtomicMarkableReference atomicMarkableReference = new AtomicMarkableReference(100, false);

    public static void main(String[] args) {
        new Thread(() -> {
            boolean marked = atomicMarkableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + " " + marked);
            //暂停几秒钟线程，等待后面的t2线程和我拿到一样的模式flag标识，都是false
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            atomicMarkableReference.compareAndSet(100, 2019, marked, !marked);

        }, "t1").start();
        new Thread(() -> {
            boolean marked = atomicMarkableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + " " + marked);
            //暂停几秒钟线程
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            boolean b = atomicMarkableReference.compareAndSet(100, 2020, marked, !marked);
            System.out.println(Thread.currentThread().getName() + "\t" + "线程CAS result: " + b);
            System.out.println(Thread.currentThread().getName() + "\t" + atomicMarkableReference.isMarked());
            System.out.println(Thread.currentThread().getName() + "\t" + atomicMarkableReference.getReference());
        }, "t2").start();

    }
}
